import { CardProps } from '@/Util/Constant';
import { BaseCard } from './baseCard';

export class Card extends BaseCard {
    private isChoice: boolean = false;
    private vx: number = 0;
    private vy: number = 0;
    private startX: number = 0;
    private startY: number = 0;
    private moveX: number;
    private moveY: number;
    constructor(props: CardProps) {
        super(props)
        this.controller.app.ticker.add(this.moveTicker)
        this.createCard()
        this.bindEvent()
    }

    private bindEvent() {
        let container = this.cardContainer as any
        container.interactive = true;
        container.on('mousedown', () => {
            this.controller.startMultipleChoice(), this.clickEventHandler()
        });
        container.on('mousemove', this.clickEventHandler);
        document.addEventListener('mouseup', () => this.controller.stopMultipleChoice())
    }

    private clickEventHandler = () => {
        let card = {
            cardNum: this.cardNum,
            cardIcon: this.cardIcon
        }
        if (this.vx || this.vy || !this.controller.isMultipleChoice) return;//如果正在移动，则跳出
        if (this.controller.isMultipleChoice && this.controller.isNowMultipleChoiceCard(card)) return

        if (!this.isChoice) {
            this.controller.choiceCard(card)
            this.choiceCard()
        } else {
            this.controller.cancelChoiceCard(card)
            this.choiceCard(true)
        }
    }

    choiceCard(isCancel?: boolean) {
        this.isChoice = !this.isChoice
        if (isCancel) {
            this.vy = 3 * this.scaleSize
            this.moveY = 30 * this.scaleSize
        } else {
            this.vy = -3 * this.scaleSize
            this.moveY = -30 * this.scaleSize
        }
        this.startY = this.cardContainer.y
    }

    merge(posX: number) {
        this.vx = posX > this.cardContainer.x ? 5 : -5
        this.moveX = posX - this.cardContainer.x
        this.startX = this.cardContainer.x
    }

    private moveTicker = (delta: number) => { // 知道绝对位置一定能算出相对位置, 因此只需要用相对偏移量就够
        if (!this.cardContainer) return;
        if (Math.abs(this.cardContainer.y - this.startY) >= Math.abs(this.moveY)) {
            this.cardContainer.y = this.startY + this.moveY // 如果超出需要归为，否则可能会有偏移
            this.startY = this.cardContainer.y
            this.vy = 0
            return;
        }
        if (Math.abs(this.cardContainer.x - this.startX) >= Math.abs(this.moveX)) {
            this.cardContainer.x = this.startX + this.moveX
            this.startX = this.cardContainer.x
            this.vx = 0
            return;
        }

        this.cardContainer.x += this.vx * delta
        this.cardContainer.y += this.vy * delta
    }

}